/**
 * @File   : ProjectPermission.js
 * @Author : xue.xiaoBing
 * @Date   : 2020/12/17
 * @Desc   : 项目权限
 **/

import {connect} from "react-redux";
import React, {Component} from "react";
import {Row, Col, Tabs, Button, Divider, Collapse, Switch, notification, Modal} from "antd";
import {
  DeleteOutlined,
  ExclamationCircleOutlined,
  PlusOutlined,
  CheckSquareFilled,
  CloseSquareFilled,
  TagTwoTone
} from '@ant-design/icons';

import UnitTitle from "src/components/Title/UnitTitle/UnitTitle";
import {getProjectRole, changeProjectRole} from "src/api/request";

import "./ProjectPermission.sass"

const {TabPane} = Tabs;
const {confirm} = Modal;
const {Panel} = Collapse;

class ProjectPermission extends Component {
  constructor(props) {
    super(props);
    this.state = {
      resourceList: [],
      roleList: [],
      roleId: [],
      permissionList: {},
      initPermission: {},
      newRole: ''
    };
  }

  componentDidMount() {
    this.props.getProjectRole( this.props.match.params.project_id)
      .then(
        ret => {
          // 获取角色信息
          let roleId = [];
          let roleList = [];
          let resourceList = [];
          let permissionList = {};

          for (let role of ret.data.results) {
            roleId.push(role.id);
            roleList.push(role.name);
            permissionList[role.name] = JSON.parse(role.permissions);
            resourceList.push(Object.keys(JSON.parse(role.permissions)))
          }

          // 更新状态
          this.setState({
            roleId: roleId,
            roleList: roleList,
            resourceList: resourceList[0],
            permissionList: permissionList,
            initPermission: permissionList[roleList[0]]
          });
        }
      )
  }

  openNotificationWithIcon = (type, content) => {
    notification[type]({
      message: '操作成功',
      description: content
    });
  };

  deleteRole = (index) => {
    let that = this;
    confirm({
      title: '删除该角色?',
      icon: <ExclamationCircleOutlined/>,
      content: '该角色将会从你的项目角色列表中删除！',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        const roleList = that.state.roleList;
        roleList.splice(index, 1);
        that.setState({
          roleList: roleList
        });
        that.openNotificationWithIcon('success', '成功的将该角色从角色列表中删除！')
      },
      onCancel() {
        console.log('Cancel');
      },
    })
  };

  inputChange = (e) => {
    this.setState({
      newRole: e.target.value
    })
  };

  addRole = () => {
    const {roleList, newRole, permissionList, initPermission} = this.state;
    roleList.push(newRole);
    permissionList[newRole] = initPermission;
    this.setState({
      roleList: roleList,
      permissionList: permissionList
    });
    this.openNotificationWithIcon('success', '角色添加成功，请为其分配权限！')
  };

  changePermission = (item, resource_item, permission_info_item) => {
    console.log(item, resource_item, permission_info_item);
    let value = this.state.permissionList[item][resource_item][permission_info_item];
    this.setState({
        permissionList: {
          ...this.state.permissionList,
          [item]: {
            ...this.state.permissionList[item],
            [resource_item]: {
              ...this.state.permissionList[item][resource_item],
              [permission_info_item]: !value
            }
          }
        }
      },
      () =>
        this.props.changeProjectRole(
          this.props.match.params.project_id,
          this.state.roleId[this.state.roleList.indexOf(item)],
          {"permissions": JSON.stringify(this.state.permissionList[item])})
    );

    this.openNotificationWithIcon('success', '权限修改成功！')
  };

  dealPermissionList = (data) => {
    let retList = [];
    Object.values(data).map(item => item ? retList.push(1) : retList.push(0));
    return retList
  };

  dealPermissionCount = (data) => {
    return Object.values(data).filter(item => item === true).length;
  };


  render() {
    const {roleList, permissionList, resourceList} = this.state;
    const {auth_id, project_id} = this.props.match.params;
    console.log(auth_id, project_id)
    return (
      <div className={'pv-project-permission'}>
        <UnitTitle mainTitle={'项目'} subTitle={'项目权限'}/>
        <Tabs className='role-tabs' tabPosition='left' size='large'>
          {roleList.map((item, index) => {
            return (
              <TabPane className={'tab-pane'} tab={item} key={index}>
                <Row>
                  <Button type={"danger"} icon={<DeleteOutlined/>} onClick={this.deleteRole.bind(this, index)}
                          className={'delete-btn'}>
                    删除
                  </Button>
                </Row>
                <Row className={'role'}>
                  <div><span>{item}</span></div>
                </Row>
                <Row className={'permission-list'}>
                  <Divider/>
                  <Collapse
                    bordered={false}
                    className={'collapse'}
                    expandIconPosition='right'
                  >
                    {resourceList.map((resource_item, resource_index) => {
                      return (
                        <Panel header={resource_item} key={resource_index}
                               extra={
                                 <div className={'permission-show'}>
                                   <span>{this.dealPermissionCount(permissionList[item][resource_item])}/{Object.keys(permissionList[item][resource_item]).length} &nbsp;&nbsp;</span>
                                   {this.dealPermissionList(permissionList[item][resource_item]).map((permissionSquaer, index) => {
                                     return (
                                       permissionSquaer === 1
                                         ? (<CheckSquareFilled className={'check-icon'} key={index}/>)
                                         : (<CloseSquareFilled className={'close-icon'} key={index}/>)
                                     )
                                   })}
                                 </div>
                               }>
                          <div className={'permission-select'}>
                            {Object.keys(permissionList[item][resource_item]).map((permission_item_key, permission_index) => {
                              return (
                                <Row className={'select-content'} key={permission_index}>
                                  <Col span={20}>
                                    {permission_item_key}
                                  </Col>
                                  <Col span={4}>
                                    <Switch className={'switch'} checkedChildren="是" unCheckedChildren="否"
                                            defaultChecked={permissionList[item][resource_item][permission_item_key]}
                                            onChange={this.changePermission.bind(this, item, resource_item, permission_item_key)}
                                    />
                                  </Col>
                                  <Divider className={'divider'}/>
                                </Row>
                              )
                            })
                            }
                          </div>
                        </Panel>
                      )
                    })}
                  </Collapse>
                </Row>
              </TabPane>
            )

          })}
          <TabPane className={'add-user-tab-pane'} tab={
            <Button className={'add-user-btn'} type="primary" icon={<PlusOutlined/>}>
              新角色
            </Button>} key="6">
            <Row className={'add-user-content'}>
              <div>
                <span><TagTwoTone className={'tag-icon'}/>&nbsp;&nbsp;角色：</span>
                <input type="text" onChange={(e) => this.inputChange(e)}/>
                <Button type="primary" onClick={this.addRole}>添加</Button><br/><br/>
                <hr/>
                <p>你将会为该项目添加一个新角色，并且请为其分配权限。</p>
              </div>
            </Row>
          </TabPane>)
        </Tabs>
      </div>
    )
  }
}

export default connect(
  null,
  {getProjectRole, changeProjectRole}
)(ProjectPermission)